package com.boot2.core.utils;

import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.ReadRender;
import com.alibaba.simpleimage.render.ScaleParameter;
import com.alibaba.simpleimage.render.ScaleRender;
import com.alibaba.simpleimage.render.WriteRender;
import com.boot2.core.exception.BusinessException;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.io.IOUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * 图片工具
 *
 * @author zhangweilin
 * @date 2016年2月19日 下午2:26:17
 * @version V1.0
 * @description
 */
@SuppressWarnings("restriction")
@CommonsLog
public class ImageUtil
{
    public static BufferedImage resizeImage(BufferedImage src, int w, int h)
    {
        int width = src.getWidth();
        int height = src.getHeight();
        float scale_w = (float) (w) / width;
        float scale_h = (float) (h) / height;

        if (scale_w > 1 && height > 1)
        {
            return src;
        }

        float min_scale = Math.min(scale_w, scale_h);
        int scaledWidth = (int) (min_scale * width);
        int scaledHeight = (int) (min_scale * height);
        // System.out.println(scaledWidth);
        // System.out.println(scaledHeight);

        BufferedImage scaledImg = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = scaledImg.createGraphics();
        g.drawImage(src, 0, 0, scaledWidth, scaledHeight, null);
        g.dispose();
        return scaledImg;
    }

    /**
     * 图片压缩
     * @param orginImage
     * @param width
     * @param height
     * @return
     */
    public static String scaleImage(File orginImage, int width, int height)
    {
        String realFullName = orginImage.getAbsolutePath();
        // System.out.println("realFullName: " + realFullName);
        // File in = new File("E:/work/eclipse/tongyeyun/doc/pic4.png"); // 原图片
        String suffix = FileUtil.getSuffix(realFullName);
        String fileName = realFullName.replace(suffix, "");
        // System.out.println("suffix: " + suffix);

        fileName = fileName + "_" + width + "_" + height + suffix;
        // System.out.println("fileName2: " + fileName);

        File outImage = new File(fileName); // 目的图片
        // File out1 = new File("E:/work/eclipse/tongyeyun/doc/ali_bak_50.jpg");
        // // 目的图片
        ScaleParameter scaleParam = new ScaleParameter(width, height); // 将图像缩略到1024x1024以内，不足1024x1024则不做任何处理

        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        WriteRender wr = null;
        try
        {
            inStream = new FileInputStream(orginImage);
            outStream = new FileOutputStream(outImage);
            ImageRender rr = new ReadRender(inStream);
            ImageRender sr = new ScaleRender(rr, scaleParam);

            wr = new WriteRender(sr, outStream);
            wr.render(); // 触发图像处理
            log.info("写入缩略图: "+outImage.getAbsolutePath());
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new BusinessException("文件处理失败", e);
        }
        finally
        {
            IOUtils.closeQuietly(inStream); // 图片文件输入输出流必须记得关闭
            IOUtils.closeQuietly(outStream);
            if (wr != null)
            {
                try
                {
                    wr.dispose(); // 释放simpleImage的内部资源
                }
                catch (SimpleImageException ignore)
                {
                    // skip ...
                    ignore.printStackTrace();
                }
            }
        }

        return outImage.getName();
    }

    /**
     * 生成数据表格图片上传至服务器 返回图片存储路径
     * 
     * @param headCells
     *            表头
     * @param list
     *            数据
     * @param imgWidth
     *            图片宽度
     * @return
     */
    public static Boolean createImage(String[] headCells, List<String[]> list, Integer imgWidth, String filePath)
    {
        Boolean flag = false;
        BufferedImage image = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try
        {
            int totalrow = list.size(); // 行
            int totalcol = headCells.length; // 列
            int rowheight = 40; // 行高
            int imageHeight = totalrow * rowheight + 20; // 高
            int imageWidth = imgWidth; // 宽
            int colwidth = (int) ((imageWidth - 20) / totalcol); // 行宽
            int startHeight = 10; // 上下边距
            int startWidth = 10; // 左边距
            int endwidth = 5; // 右边距

            image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = image.getGraphics();
            // 设置背景白色
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, imageWidth, imageHeight);
            // 设置第一行灰色
            graphics.setColor(Color.GRAY);
            graphics.fillRect(startWidth, startHeight, imageWidth - endwidth - startWidth, rowheight);

            graphics.setColor(new Color(220, 240, 240));

            // 画横线
            for (int j = 0; j < totalrow; j++)
            {
                graphics.setColor(Color.black);
                graphics.drawLine(startWidth, startHeight + j * rowheight, imageWidth - endwidth, startHeight + j * rowheight);
            }
            // 末行
            graphics.setColor(Color.black);
            graphics.drawLine(startWidth, startHeight + totalrow * rowheight, imageWidth - endwidth, imageHeight - startWidth);

            // 画竖线
            for (int k = 0; k < totalcol; k++)
            {
                graphics.setColor(Color.black);
                graphics.drawLine(startWidth + k * colwidth, startHeight, startWidth + k * colwidth, imageHeight - startWidth);
            }
            // 末列
            graphics.setColor(Color.black);
            graphics.drawLine(imageWidth - endwidth, startHeight, imageWidth - endwidth, imageHeight - startWidth);

            Font font = new Font("宋体", Font.BOLD, 20);
            graphics.setFont(font);

            // 写入表头
            for (int m = 0; m < headCells.length; m++)
            {
                graphics.drawString(headCells[m].toString(), startWidth + colwidth * m + 8, startHeight + rowheight - 10);
            }
            // 设置字体
            font = new Font("宋体", Font.PLAIN, 12);
            graphics.setFont(font);
            // 写入内容
            for (int n = 0; n < list.size(); n++)
            {
                String[] arr = list.get(n);
                for (int l = 0; l < arr.length; l++)
                {
                    // 设置第一列文字为红色
                    if (l == 0)
                    {
                        font = new Font("宋体", Font.PLAIN, 15);
                        graphics.setFont(font);
                        graphics.setColor(Color.RED);
                    }
                    else
                    {
                        font = new Font("宋体", Font.PLAIN, 20);
                        graphics.setFont(font);
                        graphics.setColor(Color.BLACK);
                    }
                    if (null==arr[l])
                    {
                        arr[l] = "";
                    }
                    graphics.drawString(arr[l].toString(), startWidth + colwidth * l + 8, startHeight + rowheight * (n + 2) - 10);
                }
            }

            // font = new Font("微软雅黑", Font.BOLD, 12);
            // graphics.setFont(font);
            // graphics.setColor(Color.RED);

            // 写备注
            // String remark = "备注：备注写在这里。";
            // graphics.drawString("", startWidth, imageHeight - 30);

            fos = new FileOutputStream(filePath);
            bos = new BufferedOutputStream(fos);

            // 暂时注释

            // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
            // encoder.encode(image);

            flag = true;
        }
        catch (Exception e)
        {
            flag = false;
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.flush();
                bos.close();
                fos.flush();
                fos.close();
            }
            catch (Exception e2)
            {
                flag = false;
                e2.printStackTrace();
            }
        }

        return flag;
    }

    // public static void main(String[] args) throws IOException
    // {
    // String intput = "D:\\AliDrive\\0.jpg";
    // String output = "D:\\AliDrive\\0_scale.jpg";
    //
    // BufferedImage img = ImageIO.read(new File(intput));
    // BufferedImage resizedImg = resizeImage(img, 500, 500);
    // ImageIO.write(resizedImg, "jpg", new File(output));
    // }
}
